package handler

import (
	"github.com/gin-gonic/gin"
	"order-ease/cache"
	"order-ease/model"
	"order-ease/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	redis_key := "login_" + username
	createData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if createData >= 3 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "错误三次,禁止登入",
		})
		return
	}
	var user model.User
	err := model.DB.Where("username = ?", username).Find(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if createData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "错误三次禁止两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "登入失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登入成功",
	})
	return
}

func RoleNodeCreate(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	nid, _ := strconv.Atoi(c.Query("nid"))

	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}

	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return

}

func UserRoleList(c *gin.Context) {
	//SELECT
	//*
	//	FROM
	//
	//roles
	//
	//LEFT JOIN user_roles ON roles.id = user_roles.rid
	//WHERE user_roles.uid = 1
	uid := c.Query("uid")

	var boos model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id = user_roles.rid").
		Where("user_roles.uid = ?", uid).
		Find(&boos)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": boos,
	})
	return

}
func RoleNodeList(c *gin.Context) {
	//SELECT
	//*
	//	FROM
	//
	//nodes
	//
	//LEFT JOIN role_nodes ON nodes.id = role_nodes.nid
	//WHERE role_nodes.rid = 1
	rid := c.Query("rid")

	var look model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id = role_nodes.nid").
		Where("role_nodes.rid = ?", rid).
		Find(&look)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": look,
	})
	return
}
